/*
 * @Author: ChunLai
 * @Date: 2022-09-06 16:59:03
 * @LastEditTime: 2025-06-03 14:27:01
 * @Description: 格式化数据
 * @FilePath: \02.bldinsure\src\methods\format.js
 */
// 身份证号(显示)
// replace(/[^\w]/g, "").replace(/(\d{6})(\d{8})(?=[0-9a-zA-Z])/g, "$1 $2 ")
export const idNumFormat = (val, type = "c") => {
  if (typeof val !== "string" || val === "") return "";
  let res = val.replace(/[^\w]/g, ""); // 移除非字母数字字符
  if (type === "s") {
    // 格式化身份证号，隐藏中间部分
    res = res.replace(/(\d{6})\d*([0-9a-zA-Z]{4})/g, "$1********$2");
  } else {
    // 格式化其他类型，插入空格
    res = res.replace(/(\d{6})(\d{8})(?=[0-9a-zA-Z])/g, "$1 $2 ");
  }
  return res;
};

// 手机号(显示)
export const tellPhoneFormat = (phone, type = "c") => {
  phone = String(phone);
  // 边界条件处理：如果电话号码长度小于7位，返回原值
  if (phone.length < 7) {
    return phone;
  }
  let res = "";
  if (type === "s") {
    res = phone.replace(/(\d{3})\d*(\d{4})/g, "$1***$2");
  } else if (type === "c") {
    res = phone.replace(/(\d{3})(\d{4})/g, "$1 $2 ");
  } else {
    // 如果 type 不是 "c" 或 "s"，返回原始号码
    res = phone;
  }
  return res;
};

// 银行账号(显示)
export const accountCodeFormat = (value) => {
  if (value) {
    return value.replace(/(\d{4})(?=\d)/g, "$1 ");
  } else {
    return "";
  }
};

export const rebackUrlPath = (pname = "", filtArr = []) => {
  // 获取 window.location 的相关属性，并进行空值检查
  const origin = window.location.origin || "";
  const pathname = window.location.pathname || "";
  const search = formatUrlSearch();
  const hash = window.location.hash || "";
  const winHash = hash.split("?");
  let hash_val = `${winHash[0]}`;
  if (pname) {
    hash_val = `${pname}`;
  }
  let res = `${origin}${pathname}${search}${hash_val}`;
  if (filtArr.length > 0) {
    filtArr.forEach((item) => {
      res = filterFieldValue(res, item);
    });
  }
  return res;
};
// 过滤链接多余字段
export const filterFieldValue = (strs, name = "") => {
  // 边界条件处理
  if (!strs || strs.trim() === "") {
    return strs; // 如果输入为空或仅包含空格，直接返回
  }
  try {
    const arr = strs.split("#/");
    const queryParts = arr[0].split("&");
    const filteredParts = queryParts.filter((part) => {
      // 如果 name 为空字符串，则不进行过滤
      if (name === "") {
        return true;
      }
      return !part.startsWith(`${name}=`); // 更精确地匹配 key=value 格式
    });
    let res = filteredParts.join("&");
    if (arr[1]) {
      res += `#/${arr[1]}`;
    }
    return res;
  } catch (error) {
    // 异常处理
    console.error("methods/format->filterFieldValue", error);
    return strs; // 如果发生异常，返回原始输入
  }
};

export const filterRebackPath = (filterArr = []) => {
  const winLoc = `${window.location.origin}${window.location.pathname}`;
  let queryParams = "";
  const prmsArr = formatUrlSearch()
    .slice(1)
    .split("&")
    .filter((item) => item.trim() !== ""); // 去掉前缀 "?"+过滤空字符串

  // 筛选查询参数
  const filteredParams = prmsArr
    .map((param) => param.split("="))
    .filter(([key]) => !filterArr.includes(key)) // 排除需要过滤的参数
    .map(([key, value]) =>
      value ? `${encodeURIComponent(key)}=${encodeURIComponent(value)}` : ""
    ) // 重新编码参数
    .filter((item) => item.trim() !== ""); // 过滤空字符串
  if (filteredParams.length > 0) {
    queryParams = `?${filteredParams.join("&")}`;
  }
  let hash_val = "";
  if (window.location.hash) {
    const hashArr = window.location.hash.split("?");
    hash_val = `${hashArr[0]}`;
  }
  return `${winLoc}${queryParams}${hash_val}`;
};

export const fmtWanYuan = (value) => {
  return value % 10000 === 0 ? `${value / 10000}万` : value;
};

export const safeParseJSON = (str) => {
  try {
    return str ? JSON.parse(str) : null;
  } catch (e) {
    console.error("Failed to parse JSON:", e);
    return null;
  }
};

export const formatUrlSearch = () => {
  // 提取 URL 查询字符串部分
  const url = window.location.search;
  if (!url) {
    return "";
  }
  const res = url
    .split("?")
    .filter((e) => e !== "")
    .join("&");
  // console.log(arr);
  return `?${res}`;
};

// 辅助函数：安全地检查对象是否包含某个属性
export const hasProperty = (obj, key) =>
  obj && typeof obj === "object" && obj.hasOwnProperty(key);

// 辅助函数：安全地获取数组的第一个元素
export const getFirstItem = (arr) =>
  Array.isArray(arr) && arr.length > 0 ? arr[0] : null;

export const getCodeName = (value, list = []) => {
  if (list.length === 0) return "";
  const obj = list.find((e) => e.value == value);
  if (obj && obj.label) {
    return obj.label;
  }
  const len = list.length;
  for (let i = 0; i < len; i++) {
    const item = list[i];
    if (item.children && item.children.length > 0) {
      const res = getCodeName(value, item.children);
      if (res) {
        return res;
      }
    }
  }
};
